import 'package:flutter/material.dart';
import 'package:ui_demo/util/layout_log_print.dart';
import 'package:ui_demo/util/print_util.dart';

class SlideTransitionPage extends StatefulWidget {
  const SlideTransitionPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _SlideTransitionPageState();
}

class _SlideTransitionPageState extends State<SlideTransitionPage>
    with SingleTickerProviderStateMixin {
  late final AnimationController _controller;

  @override
  void initState() {
    super.initState();

    /// 重复播放，持续时间为5秒的动画控制器
    _controller = AnimationController(
      duration: const Duration(seconds: 30),
      vsync: this,
    )..repeat(reverse: true);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Container(
            color: Colors.black12,
            height: 600,
            width: 800,
            child: LayoutBuilder(
              builder: (BuildContext context, BoxConstraints constraints) {
                /// 需要平移的Widget 宽高
                const childHeight = 10.0;
                const childWidth = 15.0;

                LogUtils.d("childHeight:$childHeight");
                LogUtils.d("childWidth:$childWidth");


                /// 父布局的宽高
                final parentWidth = constraints.maxWidth;
                final parentHeight = constraints.maxHeight;
                LogUtils.d("parentWidth:$parentWidth");
                LogUtils.d("parentHeight:$parentHeight");

                /// 动画起点是左上角
                const startOffset = Offset(0, 0);

                /// 动画终点右下角（父布局宽高 - 子控件宽高）/子控件宽高
                /// 因为平移时子控件大小会占用一部分空间所以需要减去
                final dx = (parentWidth - childWidth) / childWidth;
                final dy = (parentHeight - childHeight) / childHeight;
                const endOffset = Offset(1, 1);

                LogUtils.d("dx:$dx");
                LogUtils.d("dy:$dy");

                /// 补间动画
                final offsetAnimation =
                    Tween<Offset>(begin: startOffset, end: endOffset)
                        .animate(_controller);

                return LayoutLogPrint(
                    child: SlideTransition(
                  position: offsetAnimation,
                  child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        LayoutLogPrint(
                            child: Container(
                          height: 10,
                          width: 10,
                          color: Colors.red,
                          child: const Text(""),
                        )),
                      ]),
                ));
              },
            ),
          )
        ],
      ),
    );
  }
}
